package com.github.shiqiyue.app.config.security;


import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.utils.ResponseUtils;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * 登录-验证码校验过滤器
 * @author wenyao.wu
 */
@Slf4j
public class LoginCaptchaFilter extends OncePerRequestFilter {


    /***
     * 登录地址
     */
    @Setter
    private String loginUrl = "/api/sys/login/login";

    /***
     * 验证器
     */
    @Setter
    private LoginCaptchaValidator loginCaptchaValidator;

    /***
     * 验证码属性名
     */
    @Setter
    private String captchaAttributeName = "captcha";


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if(!loginUrl.equals(servletPath)){
            filterChain.doFilter(request, response);
            return;
        }
        String captcha = request.getParameter(captchaAttributeName);
        if(StringUtils.isEmpty(captcha)){
            log.warn("验证码不能为空");
            ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail("验证码不能为空")), response);
            return;
        }
        if(!loginCaptchaValidator.isLoginCaptchValid(captcha, request, response)){
            log.warn("验证码错误，请重新获取验证码");
            ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail("验证码错误，请重新获取验证码")), response);
            return;
        }
        filterChain.doFilter(request, response);
        return;
    }

    /***
     * 登录验证码- 验证器
     */
    public interface LoginCaptchaValidator {
        /***
         * 是否有效
         * @param code 验证码
         * @param httpServletRequest
         * @param httpServletResponse
         * @return
         */
        public Boolean isLoginCaptchValid(String code, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse);
    }
}
